const util = require('../../utils/util.js');
Page({
  /**
   * 页面的初始数据
   */
  data: {

    specList: [],
    showpopup: false,
    id: '',
    goodsId: "",
    goodsName: "",
    addressId: '',
    goodsCount: 1,
    notes: '',
    addrLine1: '',
    addrLine2: '',
    payLoading: false,
    money: '',
    money2: '',
    topImage: '',
    detailImage: ''

  },
  doAdd() {
    let goodsCount2 = this.data.goodsCount + 1;
    if (goodsCount2 > 200) {
      goodsCount2 = 200;
    }
    this.setData({
      goodsCount: goodsCount2
    })
    const d = this.data;
    this.setData({
      money2: (d.money * d.goodsCount).toFixed(2)
    })
  },
  doDel() {
    let goodsCount2 = this.data.goodsCount - 1;
    if (goodsCount2 <= 0) {
      return
    }
    this.setData({
      goodsCount: goodsCount2
    })
    const d = this.data;
    this.setData({
      money2: (d.money * d.goodsCount).toFixed(2)
    })
  },
  numBindblur() {
    let n = this.data.goodsCount;
    if (n === '') {
      this.setData({
        goodsCount: 1
      })
    } else if (n > 200) {
      this.setData({
        goodsCount: 200
      })
    } else if (n < 1) {
      this.setData({
        goodsCount: 1
      })
    } else if (n % 1 != 0) {
      this.setData({
        goodsCount: Math.floor(n)
      })
    } else {
      return parseInt(n)
    }
    const d = this.data;
    this.setData({
      money2: (d.money * d.goodsCount).toFixed(2)
    })
  },
  numBindblur2() {
    const d = this.data;
    this.setData({
      money2: (d.money * d.goodsCount).toFixed(2)
    })
  },
  doBack() {
    wx.navigateBack({
      delta: 1
    })
  },
  nbuy() {
    const AccessToken = wx.getStorageSync('AccessToken');
    const user = wx.getStorageSync('user');
    if (AccessToken && user && user.roleId) {
      this.goodsSpecQry();
      const money = this.data.money;
      this.setData({
        showpopup: true,
        money2: money,
        goodsCount: 1
      })
    } else {
      wx.showModal({
        title: '温馨提示',
        content: '请先登录以便获得更好的体验',
        confirmColor: '#F08302',
        showCancel: true,
        success(res) {
          if (res.confirm) {
            wx.navigateTo({ url: "/pages/login/index" })
          }
        }
      })
    }


    // wx.navigateTo({ url: '/page4/addresslist/index' })
  },
  nbuy2() {
    const d = this.data;
    this.setData({
      money2: (d.money * d.goodsCount).toFixed(2)
    })
    console.log('nbuy2')
    if (this.data.payLoading) {
      return
    }
    // wx.navigateTo({ url: '/page4/payresult/index' })
    const postData = this.data;
    console.log(postData)
    if (!postData.addressId) {
      wx.showModal({
        title: '温馨提示',
        content: '请选择收货地址！',
        confirmColor: '#F08302',
        showCancel: false
      })
      return
    }
    if (!postData.goodsCount || postData.goodsCount < 0) {
      wx.showModal({
        title: '温馨提示',
        content: '商品数量不能为空！',
        confirmColor: '#F08302',
        showCancel: false,
        success(res) {
        }
      })
      return
    }
    if (!postData.goodsId) {
      wx.showModal({
        title: '温馨提示',
        content: '商品不能为空！',
        confirmColor: '#F08302',
        showCancel: false,
        success(res) {
        }
      })
      return
    }
    let flag = false, specItemBos = [], specItemBosItem = {};
    try {
      postData.specList.forEach(item => {
        flag = false, specItemBosItem = {};
        item.valueBos.forEach(item2 => {
          if (item2.ch) {
            flag = true;
            specItemBosItem.name = item.name;
            specItemBosItem.valueBos = [
              {
                "value": item2.value
              }
            ]
          }
        })
        specItemBos.push(specItemBosItem)
        if (!flag) {
          throw item.name + '不能为空！'
        }
      })
    } catch (err) {
      wx.showModal({
        title: '温馨提示',
        content: err,
        confirmColor: '#F08302',
        showCancel: false,
        success(res) {
        }
      })
      return
      // 处理所有异常的代码
    }
    this.setData({
      payLoading: true
    })
    util.https('goodsMgmt/goodsBuy', {
      goodsId: postData.goodsId,
      addressId: postData.addressId,
      goodsCount: postData.goodsCount,
      notes: postData.notes,
      specItemBos: specItemBos,
    }, (res) => {
      console.log(res)
      this.doWxPay(res.timeStamp, res.nonceStr, res.packageValue, res.signType, res.paySign)
    }, (res) => {
      this.setData({
        payLoading: false
      })
      wx.showModal({
        title: '温馨提示',
        content: res.errorMsg,
        confirmColor: '#F08302',
        showCancel: false,
        success(res) {
        }
      })
    })
  },
  doWxPay(timeStamp, nonceStr, packageValue, signType, paySign) {
    console.log('wx.requestPayment')
    const _this = this;
    wx.requestPayment
      (
        {
          "timeStamp": timeStamp,
          "nonceStr": nonceStr,
          "package": packageValue,
          "signType": signType,
          "paySign": paySign,
          "success": function (res) {
            console.log(res)
            wx.setStorageSync('payresult', { money: _this.data.money2 });
            wx.navigateTo({ url: '/page4/payresult/index' })
          },
          "fail": function (res) {
            console.log('fail');
            console.log(res);
            wx.showModal({
              title: '温馨提示',
              content: '支付未完成！',
              confirmColor: '#F08302',
              showCancel: false,
              success(res) {
              }
            })
          },
          "complete": function (res) {
            _this.setData({
              payLoading: false
            })
          }
        }
      )
  },
  onClose() {
    console.log('onClose')
    this.setData({
      showpopup: false
    })
  },
  getDeatils() {
    util.https('goodsMgmt/goodsDetailQry', {
      "goodsId": this.data.id
    }, (res) => {
      console.log(res)
      const resDataDetail = res.goodsDetailBo, resData = res.goodsBo;
      this.setData({
        goodsId: resDataDetail.goodsId,
        topImage: resDataDetail.imageTop,
        detailImage: resDataDetail.image,
        money: resData.price1,
        goodsName: resData.name
      })

    }, (res) => {
      wx.showModal({
        title: '温馨提示',
        content: res.errorMsg,
        confirmColor: '#F08302',
        showCancel: false,
        success(res) {
        }
      })
    })
  },
  goodsSpecQry() {
    util.https('goodsMgmt/goodsSpecQry', {
      "goodsId": this.data.id
    }, (res) => {
      console.log(res)
      this.setData({
        specList: res.specs
      })

    }, (res) => {
      wx.showModal({
        title: '温馨提示',
        content: res.errorMsg,
        confirmColor: '#F08302',
        showCancel: false,
        success(res) {
        }
      })
    })
  },
  clickItemSelect(e) {
    const data = e.currentTarget.dataset;
    console.log(data);
    const list = this.data.specList;
    list.forEach(item2 => {
      if (item2.name == data.list.name) {
        item2.valueBos.forEach((item => {
          if (item.value == data.item.value) {
            item.ch = true;
          } else {
            item.ch = false;
          }
        }));
      }

    })
    console.log(list)
    this.setData({
      specList: list
    })
  },
  doAddress() {
    wx.setStorageSync(
      'address_get_type',
      1
    );
    wx.navigateTo({ url: '/page5/addresslist/index' });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('onload')
    console.log(options)
    if (options && options.id) {
      this.setData({
        id: options.id,
      });
      this.getDeatils();
    } else {
      wx.showModal({
        title: '温馨提示',
        content: '非法参数访问！',
        confirmColor: '#F08302',
        showCancel: false,
        success(res) {
        }
      })
    }

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const addressItem = wx.getStorageSync('address_get');
    if (addressItem) {
      this.setData({
        addressId: addressItem.id,
        addressName: addressItem.name,
        addrLine1: addressItem.addrLine1,
        addrLine2: addressItem.addrLine2,
      })
    }
    //  else {
    //   let resData = wx.getStorageSync('zhenxuan');
    //   if (resData) {
    //     this.setData({
    //       id: resData.id,
    //       money: resData.price2,
    //     });
    //     this.getDeatils();
    //   };

    // }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },
  onShareAppMessage() {

  },


})